package com.shycloud.mido.gateway.handler;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Producer;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.constant.SecurityConstants;
import com.shycloud.mido.gateway.util.RSAUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

/**
 * @author npc
 * @date 2018/7/5
 * 验证码生成逻辑处理类
 */
@Slf4j
@Component
@AllArgsConstructor
public class ImageCodeHandler implements HandlerFunction<ServerResponse> {
	private static final String JPEG = "jpeg";
	private final Producer producer;
	private final RedisTemplate redisTemplate;

	private static Log logger = LogFactory.getLog(ImageCodeHandler.class);

	@Override
	public Mono<ServerResponse> handle(ServerRequest serverRequest) {
		//TODO 加入验签逻辑
		Map map = (Map)serverRequest.exchange().getRequest().getHeaders();

//		Map map = new HashMap();
		logger.info(JSONObject.toJSONString(map));

		if (!map.containsKey("platform")) {
		} else if (map.containsKey("sign")) {
			String sign = ((List<String>)map.get("sign")).get(0);
			map.remove("sign");
			map.remove("host");
			map.remove("user-agent");
			map.remove("accept-encoding");
			map.remove("content-length");
			map.remove("content-type");
			map.put("Authorization", (List<String>)map.get("authorization"));
			map.remove("authorization");

			Map<String, String> concatMap = new HashMap();
			concatMap.put("Authorization", ((List<String>)map.get("Authorization")).get(0));
			concatMap.put("platform", ((List<String>)map.get("platform")).get(0));
			concatMap.put("rand", ((List<String>)map.get("rand")).get(0));
			concatMap.put("timestamp", ((List<String>)map.get("timestamp")).get(0));
			TreeMap<String, String> orderMap = new TreeMap(concatMap);

			StringBuffer conStr = new StringBuffer("appId=jykj_happyzebra&");
			for (Map.Entry entry : orderMap.entrySet()) {
				conStr.append((String)entry.getKey() + "=" + (String)entry.getKey() + "&");
			}

			String concatString = conStr.toString();

			try {
				String decrypted = RSAUtil.decrypt(sign, RSAUtil.getPrivateKey(RSAUtil.privateKey));
				if (!decrypted.equals(concatString)) {
					logger.debug("验签失败!");
					return returnFail();
				}
				logger.debug("验签通过!");
			} catch (Exception e) {
				logger.error("Error when verify sign!", e);
				return returnFail();
			}
		} else {
			return returnFail();
		}

		//生成验证码
		String text = producer.createText();
		log.info("本次生成验证码为: " + text);
		BufferedImage image = producer.createImage(text);

		//保存验证码信息
		String randomStr = serverRequest.queryParam("randomStr").get();
		redisTemplate.opsForValue().set(CommonConstants.DEFAULT_CODE_KEY + randomStr, text
				, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);

		// 转换流信息写出
		FastByteArrayOutputStream os = new FastByteArrayOutputStream();
		try {
			ImageIO.write(image, JPEG, os);
		} catch (IOException e) {
			log.error("ImageIO write err", e);
			return Mono.error(e);
		}

		return ServerResponse
				.status(HttpStatus.OK)
				.contentType(MediaType.IMAGE_JPEG)
				.body(BodyInserters.fromResource(new ByteArrayResource(os.toByteArray())));
	}

	private Mono<ServerResponse> returnFail() {
		JSONObject message = new JSONObject();
		message.put("status", -1);
		message.put("data", "鉴权失败");
//		byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
//		DataBuffer buffer = response.bufferFactory().wrap(bits);
		return ServerResponse
				.status(HttpStatus.UNAUTHORIZED)
				.contentType(MediaType.APPLICATION_JSON_UTF8)
				.body(BodyInserters.fromObject(message));
	}
}